import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    // 用于保存当前登录用户所拥有的角色列表信息
    roles: [],
    // 用于保存当前登录用户所拥有的菜单URL集合(即所拥有的菜单权限，用于在前端进行按扭级别的权限控制)
    permissions: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 为permissions数组赋值
  SET_PERMI(state, permissions) {
    state.permissions = permissions
  },
  // 负责为state中的roles角色列表赋值
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, code } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, code: code }).then(response => {
        const { data } = response
        // 生成token
        const tokenStr = data.tokenHead + data.token
        // 调用modules/user.js中actions里定义的setToken方法完成对state里的token赋值
        commit('SET_TOKEN', tokenStr)
        // 为登录名赋值
        commit('SET_NAME', username)
        // 为头像赋值
        commit('SET_AVATAR', data.avatar)
        setToken(tokenStr)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info 获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(data => {
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        // 先从data中解构出admin操作员对象
        const { admin } = data
        // 再从admin操作员对象中解构出roles角色列表、用户名、头像
        const { roles, name, userFace } = admin
        // 接着再从data中解构出当前登录用户所拥有的菜单URL集合(即所拥有的菜单权限，用于在前端进行按扭级别的权限控制)
        const { permissions } = data
        // 提交SET_PERMI事件，实现将后端响应过来的菜单URL集合赋值给permissions数组进行保存
        commit('SET_PERMI', permissions)
        // 再提交SET_ROLES事件，实现为state中的roles角色数组赋值
        commit('SET_ROLES', roles)

        // 给state中name用户名赋值
        commit('SET_NAME', name)
        // 给state中avatar用户头像赋值
        commit('SET_AVATAR', userFace)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')

        // 提交menu.js模块中的RESET_ROUTERS方法，实现填空menu.js中state里定义的routers数组中的数据 语法：commit("模块名/方法名", {}, { root: true });
        // 如果想触发其他模块的mutation动态更新state，则需要借助参数root, 注：参数二不能省略
        commit('menu/RESET_ROUTERS', {}, { root: true })
        // 另外如果想模块 B的actions中调用模块A的actions，语法：
        // dispatch("模块名/方法名", {}, { root: true });

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  // remove token
  setToken({ commit }, token) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('SET_TOKEN', token)
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
